package com.funtl.screw.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.funtl.screw.admin.entity.SysDict;
import com.funtl.screw.admin.entity.SysDictItem;
import com.funtl.screw.admin.mapper.SysDictItemMapper;
import com.funtl.screw.admin.mapper.SysDictMapper;
import com.funtl.screw.admin.service.SysDictService;
import com.funtl.screw.common.core.constant.CacheConstants;
import com.funtl.screw.common.core.constant.enums.DictTypeEnum;
import com.funtl.screw.common.core.util.ResponseResult;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 字典表
 *
 * @author Lusifer
 * @since 2019/03/19
 */
@Service
@AllArgsConstructor
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService {

    private final SysDictItemMapper dictItemMapper;

    /**
     * 根据ID 删除字典
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
    public ResponseResult<Boolean> removeDict(Long id) {
        SysDict dict = this.getById(id);
        // 系统内置
        if (DictTypeEnum.SYSTEM.getType().equals(dict.getSystemFlag())) {
            return ResponseResult.failed("系统内置，不可删除");
        }

        baseMapper.deleteById(id);
        dictItemMapper.delete(Wrappers.<SysDictItem>lambdaQuery().eq(SysDictItem::getDictId, id));
        return ResponseResult.ok();
    }

    /**
     * 更新字典
     */
    @Override
    @CacheEvict(value = CacheConstants.DICT_DETAILS, key = "#dict.dictType")
    public ResponseResult<Boolean> updateDict(SysDict dict) {
        SysDict sysDict = this.getById(dict.getId());
        // 系统内置
        if (DictTypeEnum.SYSTEM.getType().equals(sysDict.getSystemFlag())) {
            return ResponseResult.failed("系统内置，不可删除");
        }
        return ResponseResult.ok(this.updateById(dict));
    }

    /**
     * 同步缓存 （清空缓存）
     *
     * @return R
     */
    @Override
    @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
    public ResponseResult<Boolean> syncDictCache() {
        return ResponseResult.ok(true);
    }

}
